#include "musicServer.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <json-c/json.h>
#include "stdShared.h"

int read_line(int fd, void *ptr, int max_len)
{
    char *buffer = (char *)ptr;
    char temp;
    int n_r;
    int i = 0;
    for (i = 0; i < max_len; i++)
    {
        n_r = read(fd, &temp, 1);

        if (n_r == 0)
        {
            if(i==0)
            {
                return 0;
            }
            return i;
        }

        if (temp == '\n')
        {
            buffer[i] = temp;
            buffer[i+1] = '\0' ;
            return i+1;
        }
        else
        {
            buffer[i] = temp;
        }
    }
    if (n_r < 0)
    {
        perror("read error!");
        exit(1);
    }
    buffer[i]='\n';
    buffer[i+1]='\0';
    return i+1;
}

MusicServer::MusicServer(const std::shared_ptr<StdTcpSocket> & clientSock) : m_clientSock(clientSock)
{

}



void MusicServer::handleRegisterInfo(const std::string &info)
{
    json_object * jsonObj_1 = json_tokener_parse(info.c_str());
    if(jsonObj_1 == NULL)
    {
        std::cout << "解析失败" << std::endl;
        return;
    }

    /* json字符串解析成功 */
    int type_1 = json_object_get_int(json_object_object_get(jsonObj_1,"type"));
    const char * username_1 = json_object_get_string(json_object_object_get(jsonObj_1,"username"));


    const char *filename = "./register.txt";
    int readfd = open(filename, O_RDONLY | O_CREAT, 0644);
    if (readfd == -1)
    {
        perror("open error:");
        exit(-1);
    }

    bool accountExists = false;
    char buffer[256];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        //size_t bytesRead = read(readfd, buffer, sizeof(buffer) - 1);
        size_t bytesRead = read_line(readfd, buffer, sizeof(buffer) - 1);
        if (bytesRead <= 0)
            break;
        json_object * jsonObj_2 = json_tokener_parse(buffer);
        if(jsonObj_2 == NULL)
        {
            std::cout << "解析失败" << std::endl;
            return;
        }

        /* json字符串解析成功 */
        int type_2 = json_object_get_int(json_object_object_get(jsonObj_2,"type"));
        const char * username_2 = json_object_get_string(json_object_object_get(jsonObj_2,"username"));

        if (strcmp(username_2, username_1) == 0 )
        {
            accountExists = true;
            break;
        }
    }
    close(readfd);

    if (accountExists)
    {
        m_clientSock->sendMessage( "账号已存在！");
        // std::cout << "账号已存在！" << std::endl;
        return;
    }

    int writefd = open(filename, O_APPEND | O_WRONLY | O_CREAT, 0644);
    if (writefd == -1)
    {
        perror("open error:");
        exit(-1);
    }

    std::string dataToWrite = info + "\n";
    ssize_t writeBytes = write(writefd, dataToWrite.c_str(), dataToWrite.size());
    if (writeBytes < 0)
    {
        perror("write error");
        close(writefd);
        return;
    }

    close(writefd);

     /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(REGISTER));
    json_object_object_add(jsonObj, "username", json_object_new_string("ON_SUCCESS"));
    json_object_object_add(jsonObj, "passwd", json_object_new_string("注册成功"));

    const char *jsonStr = json_object_to_json_string(jsonObj);
    

    m_clientSock->sendMessage(jsonStr);
    // std::cout << "账号注册成功！" << std::endl;
}

void MusicServer::handleLoginInfo(const std::string &info)
{
    std::cout << "recv login message : " << info << std::endl;
}
